package com.sendi.system.action;

import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import com.sendi.system.bean.LoginInfo;
import com.sendi.system.bean.OnlineUser;
import com.sendi.system.entity.SystemPower;
import com.sendi.system.entity.User;
import com.sendi.system.entity.UserRole;
import com.sendi.system.entity.UserRoleRelation;
import com.sendi.system.socket.SocketSever;
import com.sendi.system.util.common.DateUtil;

public class LoginAction extends SysAction {
	private String login_username;
	private String login_password;	
    private String login_style; //登录风格,common,destop,leftrigth
 
 
	/*
	 * 系统在每次登录时查询角色ID，并根据些角色ID，查询该角色下的所有权限，保存在Sesion中，一个用户可能存在多个角色,
	 * 但由于角色无非就是对functionmoudle ID的一个状态列表，因此，最终权限也就可以合并
	 */
	public String  login() throws Exception
	{
		ServletContext sc=this.getServletContext();
	 	Object mtuser=sc.getAttribute("sendi_sys_user_info");
	 	Object mtrole=sc.getAttribute("sendi_sys_userRoleRelation_info");
	 	Object mtpower=sc.getAttribute("sendi_sys_moudlePower_info");
	 	if(mtuser==null||mtrole==null||mtpower==null)
	 	{
	 		getRequest().setAttribute("loginMSG", "用户相关信息未加载，无法登录");
			return "fail";
	 	}
	 	HashMap<String,User> usermap=(HashMap<String,User>)mtuser;
		HashMap<String,UserRoleRelation> userRoleRelation=(HashMap<String,UserRoleRelation>)mtrole;
		HashMap<String,SystemPower>      systemPower=(HashMap<String,SystemPower>)mtpower;
		User u=usermap.get(this.login_username);
		
		if(u==null)
		{
			this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"unknow user:"+this.login_username+"login to system","login");
			getRequest().setAttribute("loginMSG", "未知用户名登录");
			return "fail";
	 	}
		else
		{
			if(!u.getPassword().equals(this.login_password))
			{
				this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"user:"+this.login_username+"login to system","login");
				getRequest().setAttribute("loginMSG", "密码不正确");
				return "fail";
			}
			if(u.getIsactive().equals("off")&&!u.getUserId().equals("admin")) //系统管理员不能禁用
			{
				this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"user:"+this.login_username+"login to system","login");
				getRequest().setAttribute("loginMSG", "该用户已被禁用");
				return "fail";
		 	}
			//判断密码是否已过有限期2010 07 22 超级管理员不需要提示
			if(u.getIstip().equals("on")&&!u.getUserId().equals("admin"))
			{
				SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
			    Date  d=sdf.parse(u.getPwddate());
			    int p= DateUtil.diffDateD(d,new Date());
			    if(p>=u.getPwdvalicity())
			    {
			    	this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"user:"+this.login_username+"login to system","login");
					String pwdurl=getRequest().getContextPath()+"/system/modipwd.jsp";
			    	getRequest().setAttribute("loginMSG", u.getUserId()+":该用户密码已过期,请<a target='_blank' href='"+pwdurl+"'>修改密码</a>");
					return "fail";
			    }
				
			}
			
			
			 HashMap<String,String> roldidsarr=new HashMap<String,String>();
			////登录IP限制判断2010 07 22
			 //先获取该用户的所有角色，如果以限制IP登录的角色做为筛选的结果,超级管理员允许在任务IP登录
			if(!u.getUserId().equals("admin"))
			{
			 	 Collection<UserRoleRelation> urlist= userRoleRelation.values();
			 	 StringBuffer hqlb=new StringBuffer("from UserRole where isvalidataip ='on' and id in(");
				 for(UserRoleRelation urr:urlist)
				 {
				 	 if(urr.getUserid().intValue()==u.getId().intValue())
					 {
						 String t=urr.getRoleid()+"";
						 roldidsarr.put(t, t);
						 hqlb.append(t).append(",");
					 }
			 	 }
				 if(roldidsarr.size()==0) //说明该用户未分配任务角色，不能登录 
				 {
					    this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"user:"+this.login_username+"login to system","login");
						getRequest().setAttribute("loginMSG", "该用户未分配任务角色，不能登录");
						return "fail";
				 }
				 //获取所有限制IP登录的角色	 
				hqlb.append("-1000").append(") ");
				List usrole=this.getListData(hqlb.toString());
				 
				boolean canlogin=false;
				if(usrole.size()==0)canlogin=true; //说明该用户的所有角色不开启IP登录限制 
				for(Object ook:usrole)
				{
					UserRole urle=(UserRole)ook;
					if(urle.getLoginip().indexOf(getRequest().getRemoteAddr())!=-1) //只要在该角色中找到允许登录的IP，则让用户登录
					{
						canlogin=true;
						break;
					}
				}
				if(!canlogin) 
				{
					   this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"user:"+this.login_username+"login to system","login");
						getRequest().setAttribute("loginMSG", "该用户所在角色，在该终端IP下不允许登录");
						return "fail";
					
				}
 			}	 
			
			
			
			
			HttpSession hs=getSession();
			 try
			 {
			 LoginInfo 	 loginInfo=(LoginInfo)this.applicationContextHelper.appctx.getBean("loginInfo");
			 loginInfo.setUserid(u.getUserId()+"");
			 loginInfo.setUserName(u.getUserName());
			 loginInfo.setLogintime(new Date().toLocaleString());
			 loginInfo.setRequest(getRequest());
			 loginInfo.setLoginhost(getRequest().getRemoteAddr());
			 loginInfo.session=hs;
			 SocketSever socketSever=(SocketSever)this.applicationContextHelper.appctx.getBean("socketSever");
			 if(socketSever.isUsesocket())
			 {
				 HashMap<String, HashMap<String,Socket>>  socketmap=socketSever.getSocketmap();
				 
				 HashMap<String,Socket> relateuser=socketmap.get(u.getId()+""); //同一个用户的多个socket
			       
					 //登记在线用户,原则是从用户真正登录显示主界面，socket连接成功后才算登录成功，但由于socket server是全局的，
					 //没法获取sesion中的信息，所以只好在登录的action做登记,当真正登录时才将信息设成成功 
					 if(relateuser!=null&&relateuser.size()>=u.getMaxlogincount())
					 {
						 this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"login to system","login");
					     getRequest().setAttribute("loginMSG", this.login_username+",该用户登录次数已超过最大允许值:"+u.getMaxlogincount());
						 return "fail";
					 }
					 else
					 {
						 OnlineUser onlineUser=(OnlineUser)this.applicationContextHelper.appctx.getBean("onlineUser");
						 onlineUser.getLoginInfo().put(hs.getId(), loginInfo);
						 onlineUser.onlineUser.put(hs.getId(), u);
					 	 onlineUser.loginstatusmap.put(hs.getId(),"unknow"); //状态未知，2种状态login(登录),unknow状态需要在真正的socket连接建立后才能将状态改为login
						 hs.setAttribute("loginInfo",loginInfo);
					 }
					
			 	 
				/* else
				 {
					 this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"login to system","login");
				     getRequest().setAttribute("loginMSG", this.login_username+",该用户重复登录！");
					 return "fail";
				 }*/
			 	 
			 	 
			 	/* if(socketmap.get(u.getId()+"")==null) //说明用户没有重复登录
				 {
					 //登记在线用户,原则是从用户真正登录显示主界面，socket连接成功后才算登录成功，但由于socket server是全局的，
					 //没法获取sesion中的信息，所以只好在登录的action做登记,当真正登录时才将信息设成成功 
					 
					 OnlineUser onlineUser=(OnlineUser)this.applicationContextHelper.appctx.getBean("onlineUser");
					 onlineUser.getLoginInfo().put(u.getId()+"", loginInfo);
					 onlineUser.onlineUser.put(u.getId()+"", u);
				 	 onlineUser.loginstatusmap.put(u.getId()+"","unknow"); //状态未知，2种状态login(登录),unknow状态需要在真正的socket连接建立后才能将状态改为login
					 hs.setAttribute("loginInfo",loginInfo);
			 	 }
				 else
				 {
					 this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"login to system","login");
				     getRequest().setAttribute("loginMSG", this.login_username+",该用户重复登录！");
					 return "fail";
				 }*/
				 
			 }
			 else
			 {
				 hs.setAttribute("loginInfo",loginInfo);
			 }
			 
			 	hs.setAttribute("userName", u.getUserName());
				 hs.setAttribute("username", u.getUserId()+"");
				 hs.setAttribute("userid", u.getUserId()+"");
				 hs.setAttribute("user_id",u.getId()+""); //user_id为用户的主键
				 
				 
			 }catch (Exception e) {
					this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "fail", new Date().toLocaleString(),"login to system","login");
					e.printStackTrace();
					 getRequest().setAttribute("loginMSG","error:"+e.getMessage());
					return "fail";
		   }
			 
			 
			 //如果不是系统管理员则需要查询权限
			if(!u.getUserId().equals("admin"))
			{
				/* 2010 07 22
				 HashMap<String,String> roldidsarr=new HashMap<String,String>();
				 Collection<UserRoleRelation> urlist= userRoleRelation.values();
				 for(UserRoleRelation urr:urlist)
				 {
				 	 if(urr.getUserid().intValue()==u.getId().intValue())
					 {
						 String t=urr.getRoleid()+"";
						 roldidsarr.put(t, t);
					 }
			 	 }*/
			 	    HashMap<String,String> powerMap=new HashMap<String, String>();
					Collection<SystemPower> syplist=systemPower.values();
				    for(SystemPower o:syplist)
				    {
				     
				       if(roldidsarr.get(o.getRoleid()+"")!=null)
				       {
				    	   powerMap.put(o.getMoudleid()+"",o.getPowerstate()); 
				       }
			 	    }
			 	    hs.setAttribute("userSystemPower", powerMap);
		 	}
		 
			this.sysLogHelper.Log(this.login_username, getRequest().getRemoteAddr(), "success", new Date().toLocaleString(),"login to system","login");	 
		    return login_style;
	 	}
	 	
	 }
	public String logout()
	{
	 	return "logout";
	}
	public String getLogin_username() {
		return login_username;
	}
	public void setLogin_username(String login_username) {
		this.login_username = login_username;
	}
	public String getLogin_password() {
		return login_password;
	}
	public void setLogin_password(String login_password) {
		this.login_password = login_password;
	}
	public String getLogin_style() {
		return login_style;
	}
	public void setLogin_style(String login_style) {
		this.login_style = login_style;
	}
 

 
}
